﻿using System.Configuration;
using System.Threading;
using Microsoft.Practices.Unity;
using Microsoft.Practices.Unity.Configuration;

namespace CloudPms.Domain.Repository
{
    /// <summary>
    /// Unity依赖注入容器
    /// <para>--------------------------</para>
    /// <para>@Author: cnalexi@gmail.com</para> 
    /// <para>@Modify: 2012/7/11</para> 
    /// <para>@Create: 2012/2/23</para> 
    /// </summary>
    public sealed class UnityContainerService
    {
        private static volatile IUnityContainer _container;

        private static readonly object lockThis = new object();

        public static IUnityContainer GetContainer()
        {
            if(_container==null)
            {
                lock (lockThis)
                {
                    if(_container==null)
                    {
                        //var section = (UnityConfigurationSection)ConfigurationManager.GetSection("unity");

                        var fileMap = new ExeConfigurationFileMap {ExeConfigFilename = DbContextService.GetRootPath()+"unity.config"};

                        Configuration configuration = ConfigurationManager.OpenMappedExeConfiguration(fileMap,ConfigurationUserLevel.None);

                        var section = (UnityConfigurationSection) configuration.GetSection("unity");

                        _container = new UnityContainer().LoadConfiguration(section);
                        
                        //已知错误：'未能加载文件或程序集'，需检查配置文件中的映射文件是否正确
                        //section.Configure(container);

                        Thread.MemoryBarrier();
                    }
                }

            }

            return _container;
        }
    }
}
